<?php

class Start extends CI_Controller {

	public function __construct() {
            parent::__construct(); 

            $this->load->helper(array('form','url'));
            $this->load->library('form_validation');
	}
        
        public function index() {
            
            $this->load->view('start_view');
        }
        
        public function start_registration() {
            $this->load->view('register_view');
            
        }
        
        private function _create_session($user_id) {
            
            //header("Location: /dynasties2/main_interface/");
            $this->load->helper('url');
            
            //$user = $this->doctrine->em->find('ORM\Dynasties2\Users', $user_id);
            //echo 'Thanks for logging in, ' . $user->getfirstName() . ' (' . $user_id . ')!</br>';
            //session_start();
            //session_register("login");
            
            
            //$_SESSION['sessionID'] = $uniquesessionID;
            $this->load->library('user_agent');
            $this->load->library('session');
            $new_session = new ORM\Dynasties2\Sessiontracker;
            
            $new_session->setSessionLongID('0');
            $new_session->setSessionAutoID($this->session->userdata('session_id'));
            $new_session->settimeStamp(new DateTime());
            $new_session->setipAddress($this->input->ip_address());
            $new_session->setBrowser($this->agent->browser());
            $new_session->setBrowserVersion($this->agent->version());
            $new_session->setPagesVisited('0');
            $new_session->setPlatform($this->agent->platform());
            $new_session->setAgentString($this->agent->agent_string());
            $new_session->setIsMobile($this->agent->is_browser());
            $new_session->setIsBrowser($this->agent->is_mobile());
            $new_session->setSessionUser($user_id);
            $this->doctrine->em->persist($new_session);
            $this->doctrine->em->flush();
            
            //$session_value = $new_session->getID();
            //echo $new_session->getID();
            //$new_session->setSessionLongID($session_value);
            //$this->doctrine->em->persist($new_session);
            //$this->doctrine->em->flush();
            
            $_SESSION["user"] = $user_id;
            $_SESSION["identifier"] = $new_session->getID();
            $_SESSION["long_id"] = $new_session->getID();
            
            
            ///// when the user logs in and this session is created, it will check to see if they have an existing (and active)
            // family.  if so, and if only 1, it will set that family ID as a session variable.
            $which_family = $this->doctrine->em->getRepository('ORM\Dynasties2\Families')->findOneBy(array('whichUser' => $user_id));
                        
            //$this->load->library('session');
            // http://codeigniter.com/user_guide/libraries/sessions.html
            //print_r($this->session->all_userdata());
        
            
            if (is_null($which_family)) {
                // does not have a family, will get caught later and create a family
            } else {
                
                $_SESSION['active_family'] = $which_family->getID();
                
                //$familyname = $family->getfamilyname();
            }
            /////////////////
            
            redirect('/main', 'location');
        }
        
        public function login_submit() {
            session_start();
            //$this->load->library('session');
            // just need to take posted values and do a compare to see if they are valid...
            $loginvar = $this->input->post('email');
            $passvar = $this->input->post('password');
            //echo $loginvar . " and " . $passvar;
            
            
            $salted = 'LMs_bo9-14_f' . $passvar;
            $hashedpass = md5($salted);
            
            $this->load->library('encrypt');
            
            
            $user = $this->doctrine->em->getRepository('ORM\Dynasties2\Users')->findOneBy(array('email' => $loginvar));
            if (is_null($user)) {
                // no such email address
                echo 'Invalid Login<br />'; 
                
            } else {
                // email address exists
                $passcheck = $user->getPassword();
                $decrypted = $this->encrypt->decode($passcheck);
                
                if ($decrypted !== $hashedpass) {
                    // passwords do not match.
                    // no login
                    echo 'Invalid Login<br />';
                } else {
                    // passwords do match.
                    // login OK
                    $user_id = $user->getid();
                    
                    $this->_create_session($user_id);
                }
            
            }
            
            
            
            
        }
        
        
        
        public function registration_submit() {
            
            
            if ($this->_registration_validate() === FALSE) {
                $this->start_registration();
                return;    
            }
            $this->load->model('register_new_user_model');
            $this->register_new_user_model->commit_new_user();
            
        }

        
        
        
        private function _registration_validate() {
            
            $this->form_validation->set_rules('firstname', 'Firstname',
                    'required|min_length[2]|trim|max_length[15]|alpha|xss_clean');
            
            $this->form_validation->set_rules('lastname', 'Lastname',
                    'required|min_length[2]|trim|max_length[15]|alpha|xss_clean');

             $this->form_validation->set_rules('password', 'Password',
                     'required|min_length[6]|max_length[24]');

             $this->form_validation->set_rules('passconf', 'Confirm Password',
                     'required|matches[password]');

             //$this->form_validation->set_rules('email', 'E-mail',
               //   'required|valid_email|is_unique[users.email]');
             
             $this->form_validation->set_rules('email', 'E-mail', 
                     'required|valid_email|min_length[8]|trim|callback_email_check');
             
             $this->form_validation->set_rules('referral', 'Referral',
                    'min_length[3]|max_length[200]|xss_clean');

             return $this->form_validation->run();
            
        }
        
        
        
        
        
        public function email_check($str)
	{
		$user = $this->doctrine->em->getRepository('ORM\Dynasties2\Users')->findOneBy(array('email' => $str));
                if ($str == 'test')
		{
			$this->form_validation->set_message('email_check', 'The %s field can not be the word "test"');
			return FALSE;
		}
		else if (isset($user)) {
                        $this->form_validation->set_message('email_check', 'This email address is already in use');
                        return FALSE;
                } else
		{
			return TRUE;
		}
	}

        
        
}
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
